# -*- coding: utf-8 -*-
"""
@Version : 
@Author  : ChenMZ
@Time    : 2025/09/23
@File    : CPUMainView.py
@Desc    : 
@Modify  : 
"""
import time
from typing import Callable, Optional

from PyQt5 import QtGui
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QWidget, QStackedWidget, QHBoxLayout

from tool.signal_bus import CpuMonitorSignalBus
from device.dev_interface import CPU
from ui.DevMonitorUI.CpuMonitor.CpuMainUI import Ui_Form
from view.DevMonitorUIView.CpuMonitor.CPULoadPercentageMonitorView import CpuLoadPercentageView
from view.DevMonitorUIView.CpuMonitor.CPUStaticInfoMonitorView import CpuStaticInfoView


class CpuDynamicCap(QThread):
    def __init__(self, dev: CPU):
        super().__init__()
        self._dev = dev
        self._activ = False

    @property
    def is_activ(self):
        return self._activ

    def cap_end(self):
        self._activ = False

    def run(self) -> None:
        self._activ = True
        while self._activ:
            CpuMonitorSignalBus.signal_dynamic_cap_val.emit(self._dev.get_usage())
            time.sleep(.5)


class CpuMainView(QWidget, Ui_Form):
    cap_thread: CpuDynamicCap

    def __init__(self, device: CPU):
        super().__init__()
        self.setupUi(self)
        self.device = device
        self.load_percentage_page = CpuLoadPercentageView()
        self.static_info_page = CpuStaticInfoView()
        self.stackedWidget = QStackedWidget(self)

        self.initialization()
        self.init_tab()
        self.register_signal()

    def initialization(self):
        stack_layout = QHBoxLayout()
        stack_layout.addWidget(self.stackedWidget)
        self.CardWidget.setLayout(stack_layout)
        self.stackedWidget.setCurrentWidget(self.static_info_page)

    def init_tab(self):
        self.TabBar.setTabsClosable(False)
        self.TabBar.setCloseButtonDisplayMode(2)
        self.TabBar.setAddButtonVisible(False)
        self.add_sub_interface(
            "static_info_page", "CPU信息", ":/monitor/icons/monitor_static_info.svg",
            None, self.static_info_page
        )
        self.add_sub_interface(
            "load_percentage_page", "使用率", ":/monitor/icons/monitor_percentage.svg",
            None, self.load_percentage_page
        )

    def register_signal(self):
        self.TabBar.currentChanged.connect(self.tab_changer)
        CpuMonitorSignalBus.signal_get_attr_req.connect(self.get_dev_attr)
        CpuMonitorSignalBus.signal_dynamic_cap.connect(self.enable_cpu_cap)

    def add_sub_interface(
            self, route_key: str, text: str, icon: str, click_action: Optional[Callable], widget: QWidget
    ):
        self.TabBar.addTab(route_key, text, icon, onClick=click_action)
        self.stackedWidget.addWidget(widget)

    def tab_changer(self):
        current_page = self.TabBar.currentTab().routeKey()
        self.stackedWidget.setCurrentWidget(getattr(self, current_page, None))

    def get_dev_attr(self, attr_name: str):
        if attr_name != "":
            CpuMonitorSignalBus.signal_get_attr_resp.emit(
                {attr_name: getattr(self.device, attr_name, None)}
            )

    def enable_cpu_cap(self, enable: bool):
        if enable:
            if not hasattr(self, "cap_thread"):
                self.cap_thread = CpuDynamicCap(self.device)
            if self.cap_thread.is_activ:
                return
            self.cap_thread.start()
        else:
            if not hasattr(self, "cap_thread"):
                return
            self.cap_thread.cap_end()
            del self.cap_thread

    def closeEvent(self, a0: Optional[QtGui.QCloseEvent]) -> None:
        self.enable_cpu_cap(False)




